import { Exclude } from 'class-transformer'
import {
  Column,
  CreateDateColumn,
  Entity,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryColumn,
  PrimaryGeneratedColumn,
  Unique,
  UpdateDateColumn
} from 'typeorm'
import { Role } from 'src/auth/role/entities/role.entity'
import {
  IsMobilePhone,
  IsNotEmpty,
  IsOptional,
  IsString,
  Length,
  Matches
} from 'class-validator'
@Entity('user')
export class User {
  @PrimaryGeneratedColumn()
  id: number

  @Column()
  @Unique('name', ['name'])
  @IsString()
  @IsNotEmpty({ message: '用户名不能为空' })
  @Length(2, 16, { message: '用户名长度在2-16之间' })
  @Matches(/^[a-zA-Z0-9]{2,16}$/, {
    message: '用户名仅支持字母和数字'
  })
  name: string

  @Column({ nullable: false })
  @IsString()
  @IsNotEmpty({ message: '昵称不能为空' })
  @Length(2, 24, { message: '昵称长度在2-24之间' })
  nickname: string

  @Column()
  @Exclude()
  @Length(6, 16, { message: '密码长度在6-16之间' })
  @Matches(
    /^(?!^[a-zA-Z]*$)(?!^[0-9]*$)(?!^[!@#$%^&*(),.?":{}|<>]*$).{6,16}$/,
    { message: '密码必须包含大小写字母、数字、特殊字符中的至少两个' }
  )
  password: string

  @Column({ nullable: true, length: 11 })
  @IsOptional()
  @IsMobilePhone('zh-CN', {}, { message: '请输入有效的手机号' })
  phone: string

  @Column({ nullable: true })
  avatar: string

  @Column({ name: 'role_id', nullable: true })
  roleId: number

  @Column({ nullable: true })
  description: string

  @Column({ nullable: true, length: 36 })
  email: string

  @CreateDateColumn({
    type: 'timestamp',
    name: 'create_time',
    nullable: false
  })
  createTime: Date

  @UpdateDateColumn({ type: 'timestamp', name: 'update_time', nullable: true })
  updateTime: Date

  @ManyToOne(() => Role, (role) => role.id, {
    eager: true,
    onDelete: 'SET NULL'
  })
  @JoinColumn({ name: 'role_id' })
  role: Role

  @ManyToOne(() => User, (user) => user.id, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'created_by' })
  createdBy: number

  @ManyToOne(() => User, (user) => user.id, { onDelete: 'SET NULL' })
  @JoinColumn({ name: 'updated_by' })
  updatedBy: number

  constructor(user?: Partial<User>) {
    Object.assign(this, user)
  }
}

@Entity('user_role')
export class UserRole {
  @PrimaryColumn({ name: 'user_id' })
  userId: number

  @PrimaryColumn({ name: 'role_id' })
  roleId: number

  // @OneToOne(() => User, (user) => user.id)
  // @JoinColumn({ name: 'user_id' })
  // user: User

  // @OneToOne(() => Role, (role) => role.id)
  // @JoinColumn({ name: 'role_id' })
  // role: Role
}
